Garbage collection is a type of memory management where a garbage collector reclaims memory occupied by objects that are no longer in use. Garbage collection may be used and/or required by certain programming languages. In a system that employs garbage collection, some objects may be allocated on a heap managed by a garbage collector. The heap may be a portion of memory where allocated objects (e.g., records, structures, instances, or data values) reside. When an object is allocated, an unused range of memory addresses (or otherwise characterized memory or storage region) is identified on the heap, and that region of memory is used to create the object and contain its data.
The job of the garbage collector is to distinguish between allocated objects that are reachable and those that are unreachable, where an object is considered to be reachable when it is possible for any current or future executing program code to access the object or its data. An object is considered unreachable when it is not possible for any executing program code to access the object or its data. When objects are determined to be unreachable, the garbage collector may declare the memory regions they occupy to be unallocated and return this memory to the allocator for use in allocating new objects. This process is known as collecting (or garbage collecting) the objects.
Garbage collection may involve determining a set of root pointers. A root pointer is a pointer to an object stored in a garbage-collected heap where the root pointer itself is observed by a garbage collector in a location other than on the garbage-collected heap. For example, the pointer may be observed in a processor register, on a program or thread stack, in a global or thread-local variable or structure, or within a heap other than the garbage-collected heap.
Garbage collection may include determining objects that are reachable starting from the root pointers. An object may be considered reachable if it is pointed to by a root pointer or by a pointer contained in some reachable object. Pointers may be considered to be strong pointers or weak pointers. An object referred to by a strong pointer that is a root or is contained in a reachable object is considered reachable. A weak pointer, by contrast, does not affect the reachability of the object it points to. When an object has no strong pointers to it from reachable objects, it will be garbage collected in a subsequent GC cycle even if it is referred to by weak pointers.